﻿using Common;
using Common.Swagger;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SystemService;

namespace Gateway.AuthorizationFilter
{
    public class CustomerAuthorizationFilter : IAuthorizationFilter
    {
        private static SystemUrlService systemUrlService;
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            //if (systemUrlService == null)
            //{
            //    systemUrlService = Application.GetService<SystemUrlService>();
            //}
            string url = context.HttpContext.Request.Path.Value;
            if (url == "/" || url.EndsWith("swagger.json") || url.Contains(".well-known/openid-configuration") || url.Contains("/api/Login/LoginIn") || url.Contains("swagger/index.html") || url.Contains("/favicon.ico") || url.Contains("/swagger/") || url.Contains("/connect/token"))
            {
                
            }
            else
            {
                SystemUrlService systemUrlService = context.HttpContext.RequestServices.GetService(typeof(SystemUrlService)) as SystemUrlService;
                var entity = SwaggerReadSummary.ReadSummary(context.HttpContext);
                if (entity != null)
                {
                    systemUrlService.CheckAndAdd(new SystemEntity.SystemUrlEntity() { Url = url, Name = entity.Name, ApplicationName = entity.ApplicationName, ControllerName = entity.ControllerName });
                }
                Console.WriteLine(context.HttpContext.TraceIdentifier + url);
                string authorization = string.Empty;
                if (context.HttpContext.Request.Headers.ContainsKey("authorization"))
                {
                    authorization = context.HttpContext.Request.Headers["authorization"].ToString();
                }
                else if (context.HttpContext.Request.Query.ContainsKey("token"))
                {
                    authorization = context.HttpContext.Request.Query["token"];
                }
                else if (context.HttpContext.Request.Query.ContainsKey("authorization"))
                {
                    authorization = context.HttpContext.Request.Query["authorization"];
                }
                if (string.IsNullOrEmpty(authorization))
                {
                    context.HttpContext.Response.ContentType = "text/html;charset=utf-8";
                        //context.HttpContext.Response.WriteAsync(JsonConvert.SerializeObject(Result.Error("没权限")));
                        //context.HttpContext.Response.CompleteAsync();
                    
                }
                else
                {
                    
                }
            }
           
        }
    }
}
